package com.elitel.frame.base.component;

import com.elitel.frame.base.service.BaseQueryfieldService;
import com.elitel.frame.main.entity.BaseQueryfield;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * 生成缓存数据Redis Key的值
 * created by guoyanfei on 2018/12/19
 */
@Component("redisKey")
public class RedisKey {
    @Autowired
    private BaseQueryfieldService baseQueryfieldService;

    /**
     * show 通过参数生成redis key
     * create by guoyanfei on 2018/12/19
     * @param serviceId 服务ID
     * @param conQuery 参数值(格式:Map<String,String>)
     * @param serviceType 服务类型
     * @param keyType (热点key：1，普通key：0)
     * @param pageNum(redis缓存数据的页数,如果不分页该值为"")
     * @return key值
     */
    public String generate(String serviceId,Map<String,String> conQuery,String serviceType,String keyType,String pageNum){
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("serviceId_"+serviceId);
        //查询参数信息
        List<BaseQueryfield> baseQueryfields =
                baseQueryfieldService.getQueryFieldByServiceId(serviceId,1);
        if(baseQueryfields != null && baseQueryfields.size() > 0 && conQuery != null && conQuery.size() > 0){
            for (BaseQueryfield baseQueryfield: baseQueryfields) {
                String param = "";
                //获取参数code对应的值
                for(Map.Entry<String,String> str:conQuery.entrySet()){
                    if(baseQueryfield.getParametercode().equals(str.getKey())){
                        param = str.getValue();
                    }
                }
                stringBuffer.append("_"+baseQueryfield.getParametercode()+"_"+param);
            }
        }
        //设置分页
        if(pageNum != null && !pageNum.equals("")){
            stringBuffer.append("_pageNum_"+pageNum);
        }

        stringBuffer.append("_"+keyType);
        return stringBuffer.toString();
    }

    /**
     * 通过参数生成redis key
     * @param serviceId
     * @param conQuery
     * @param serviceType
     * @param keyType
     * @param pageNum
     * @return
     */
    public String generateKey(String serviceId,Map<String,String> conQuery,String serviceType,String keyType,String pageNum){
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("serviceId_"+serviceId);

        if (conQuery != null && conQuery.size() > 0){
            for(Map.Entry<String,String> str:conQuery.entrySet()){
                stringBuffer.append(String.format("_%s_%s",str.getKey(),str.getValue()));
            }
        }
        //设置分页
        if(pageNum != null && !pageNum.equals("")){
            stringBuffer.append("_pageNum_"+pageNum);
        }
        stringBuffer.append("_"+keyType);
        return stringBuffer.toString();
    }
}
